// @ts-ignore
import {nanoid} from "nanoid";

export const ImageViewToBase64WithMark = async (viewUrl: string): Promise<any> => {
    const watermark_file = await ImageViewTofileWithMark(viewUrl);
    return await blobToBase64(watermark_file)
}

export const ImageViewTofileWithMark = async (viewUrl: string) => {
    //1.view转为blod
    const orign_image_blob = await ImageUrlToBlob(viewUrl)
    //2.blob转为图片元素
    const origin_image_element: unknown = await blobToImage(orign_image_blob)
    //3.图片元素转cavans
    const watermark_canvas = await imgToCanvas(origin_image_element)
    //4.添加水印
    const watermark_blob = await watermark(watermark_canvas, "WATER MARK")
    //5 blob转文件
    return await blobtoFile(watermark_blob, "test001")
}

//下载blod
export const download = (blob: Blob | any) => {
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'image.jpg');
    document.body.appendChild(link);
    link.click();
}

export const ImageUrlToBase64 = async (url: string): Promise<any> => {
    return new Promise((resolve, reject) => {
        fetch(url).then(r => r.blob()).then(blob => {
            resolve(blobToBase64(blob))
        })
    })
}

/**
 * 将URL转为blob
 *
 * @param url
 * @constructor
 */
export const ImageUrlToBlob = async (url: string): Promise<Blob> => {
    return new Promise((resolve, reject) => {
        fetch(url).then(r => r.blob()).then(blob => {
            resolve(blob)
        })
    })
}
/**
 * 传入一个blob或者file,转换为base64
 * @param blob
 */
export const blobToBase64 = async (blob: Blob | any): Promise<string> => {
    return new Promise((resolve, reject) => {
        try {
            const reader = new FileReader()
            reader.readAsDataURL(blob)
            reader.onloadend = function (result) {
                // console.log("blobToBase64正常转换，结果是",reader.result)
                resolve(reader.result + "")
            }
        } catch (error) {
            // console.log("blobToBase64过程异常")
            resolve("")
        }
    })
}

//blob专为file
export const blobtoFile = async (blob: any, name: string): Promise<File> => {
    return new Promise((resolve) => {
        const files = new window.File([blob], name, {type: blob.type});
        resolve(files)
    })
}

export const blobToImage = async (blob: any) => {
    return new Promise((resolve, reject) => {
        let reader = new FileReader()
        reader.addEventListener('load', () => {
            let img: any = new Image()
            img.src = reader.result
            img.addEventListener('load', () => resolve(img))
        })
        reader.readAsDataURL(blob)
    })
}

export const imgToCanvas = (img: any) => {
    let canvas = document.createElement('canvas')
    canvas.width = img.width
    canvas.height = img.height
    const ctx: any = canvas.getContext('2d')
    ctx.drawImage(img, 0, 0)
    return canvas
}

export const watermark = async (canvas: HTMLCanvasElement, text: string): Promise<string> => {
    return new Promise((resolve, reject) => {
        let ctx = canvas.getContext('2d')
        // 设置填充字号和字体，样式
        // @ts-ignore
        ctx.font = "30px 宋体"
        // @ts-ignore
        ctx.fillStyle = "#FFFFFF"
        // 设置右对齐
        // @ts-ignore
        ctx.textAlign = 'right'
        // 在指定位置绘制文字，这里指定距离右下角20坐标的地方
        for (let i = 1; i < 10; i++) {
            // @ts-ignore
            ctx.fillText(text, canvas.width - 100, canvas.height - 100 * i)
        }

        // @ts-ignore
        canvas.toBlob(blob => resolve(blob))
        // const src=canvas.toDataURL('image/png')
        // resolve(src)
    })
}
/**
 * 将文件转为Buffer
 */
// export const fileToBuffer = (file: File): Promise<Buffer> => {
//     return new Promise((resolve, reject) => {
//         const reader = new FileReader();
//         reader.readAsArrayBuffer(file);
//         reader.onload = () => resolve(Buffer.from(reader.result));
//         reader.onerror = (error) => reject(error);
//     });
// }
/**
 * 上传文件到OSS,返回上传成功的文件名
 *
 * @param file
 * @param type
 */
export const useUtilsUploadFileToOSS = async (file: File, type: "audio" | "image" | "video"): Promise<string | undefined> => {
    //将file转为buffer
    const formData = new FormData()
    formData.append('file', file)
    return await $fetch("/file/upload", {
        method: 'POST',
        baseURL: useRuntimeConfig().public.baseApiurl,
        headers: {
            Accept:'*/*',
            Connection:"keep-alive",
            ContentType: 'multipart/form-data',
        },
        body: formData,
        redirect: 'follow'
    }).catch(error => console.log('error', error)) as string | undefined;

    // 创建OSS客户端实例
    // const {token, domain, region} = await Client_GET('/file/qiniu/uploadToken') as {
    //     token: string,
    //     domain: string,
    //     region: string
    // }
    // if (domain && region) {
    //     return useFileuploadFileToQiniuOSS(file, type)
    // }
    //
    // //上传阿里云
    // const {useOss, useCustomizeOss, ossConfig} = useStableDiffusionStore()
    // // 启用了自定义OSS，但是没有配置完整OSS参数
    // if (useCustomizeOss && (!ossConfig || ossConfig.ossBucket === '' || ossConfig.ossRegion === '' || ossConfig.ossRegion === '' || ossConfig.ossKey === '')) {
    //     useSnackbarStore().showErrorMessage("请先配置OSS")
    //     return
    // }
    // // 启用了OSS，没有启用自定义OSS，但是参数不全
    // if (!useCustomizeOss && (!useRuntimeConfig().public.ossBucket || !useRuntimeConfig().public.ossRegion || !useRuntimeConfig().public.ossKey || !useRuntimeConfig().public.ossSecret)) {
    //     console.log(useRuntimeConfig().public.ossKey, useRuntimeConfig().public.ossSecret)
    //     useSnackbarStore().showErrorMessage("你启用了OSS，且没有启用自定义OSS，请在环境变量中配置OSS")
    //     return
    // }
    // const client = new OSS({
    //     region: useCustomizeOss ? ossConfig.ossRegion : useRuntimeConfig().public.ossRegion, // 替换为你的OSS区域
    //     accessKeyId: useCustomizeOss ? ossConfig.ossKey : useRuntimeConfig().public.ossKey, // 替换为你的AccessKeyId
    //     accessKeySecret: useCustomizeOss ? ossConfig.ossSecret : useRuntimeConfig().public.ossSecret, // 替换为你的AccessKeySecret
    //     bucket: useCustomizeOss ? ossConfig.ossBucket : useRuntimeConfig().public.ossBucket, // 替换为你的Bucket名称
    //     secure: true, // 是否使用https
    //
    // });
    // const filename = nanoid(15)
    // let targetPath = '';
    // switch (type) {
    //     case "audio":
    //         targetPath = `aidraw/audio/${filename}.wav`;
    //         break;
    //     case "image":
    //         targetPath = `aidraw/image/${filename}.png`;
    //         break;
    //     case "video":
    //         targetPath = `aidraw/video/${filename}.mp4`;
    //         break;
    // }
    // try {
    //     // 上传文件
    //     const {url} = await client.put(targetPath, file);
    //     console.log('File uploaded to OSS:', url);
    //     return url;
    // } catch (e) {
    //     console.error('Error uploading file to OSS:', e);
    //     throw e;
    // }
}
/**
 * 上传文件到七牛OSS,返回上传成功的文件名
 *
 * @param data
 * @param type
 */
export const useFileuploadFileToQiniuOSS = async (
    data: File | Buffer,
    type?: "audio" | "image" | "video" | "other"
): Promise<string> => {
    //
    const {token, domain, region} = await Client_GET('/file/qiniu/uploadToken') as {
        token: string,
        domain: string,
        region: string
    }
    //处理域名地址名称，去除空格和末尾的/
    const domainPrefix = domain.trim().replace(/\/$/, '');

    const putExtra = {
        fname: Date.now() + ".png",
        mimeType: "image/png",
    };
    // 生成唯一的文件名
    let _pre_fix = 'temps/';
    let _after_fix = '.png';
    switch (type) {
        case 'image':
            putExtra.mimeType = 'image/png';
            _pre_fix += 'image/';
            _after_fix = '.png';
            break;
        case 'audio':
            putExtra.mimeType = 'audio/wav';
            _pre_fix += 'audio/';
            _after_fix = '.wav';
            break;
        case 'video':
            putExtra.mimeType = 'video/mp4';
            _pre_fix += 'video/';
            _after_fix = '.mp4';
            break;
        default:
            putExtra.mimeType = 'image/png';
            _pre_fix += 'others/';
            _after_fix = '.png';
            break;
    }
    const _key = _pre_fix + Date.now().toString() + _after_fix;

    console.log(token)

    const url = `https://up-${region}.qiniup.com`
    const formData = new FormData();
    formData.append('key', _key)
    formData.append('file', data);
    formData.append('token', token);
    const response = await fetch(url, {
        method: 'POST',
        body: formData,
        headers: {
            Host: `up-${region}.qiniup.com`
        }
    });
    if (response.ok) {
        console.log(response)
        return `${domainPrefix}/${_key}`;
    } else {
        throw new Error('Upload failed');
    }

}

/**
 * 根据    type?: 'image' | 'audio' | 'video' | 'text',获取路径存储路径名称
 * @param type
 */
export const getFilePath = (type?: 'image' | 'audio' | 'video' | 'text'): string => {
    const filename = nanoid(15);
    let _targetPath = `aidraw/others/temps/${filename}.png`;
    switch (type) {
        case 'image':
            _targetPath = `image/upload/${filename}.png`;
            break;
        case 'audio':
            _targetPath = `audio/upload/${filename}.wav`;
            break;
        case 'video':
            _targetPath = `video/upload/${filename}.mp4`;
            break;
        default:
            _targetPath = `others/upload/${filename}.png`;
            break;
    }
    return _targetPath;
}